import Base from "../base.js";
import adminsApi from "../../api/admins.js"
export default class extends Base {
    data = {
        rows: [],
        curPage: 1,//当前页
        eachPage: 3,//每页显示条数
        total: 0,//总条数
        maxPage: 0,//总页数
    }
    _id = ""
    render() {
        this.$el.html(
            `
                <table id="demo" lay-filter="test"></table>
                <div id="test1"></div>
            `
        )
        layui.use('table', () => {
            this.table = layui.table;

            //第一个实例
            this.table.render({
                elem: '#demo'
                , cols: [[ //表头
                    , { field: 'adminName', title: '管理员', }
                    , {
                        field: '', title: '操作', templet: function (res) {
                            return `
                                <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
                                <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                            `
                        }
                    }
                ]]
            });

        });

        layui.use('laypage', () => {
            this.laypage = layui.laypage;
        });
    }
    async getList() {
        const { curPage, eachPage } = this.data
        this.data = await adminsApi.getList({ curPage, eachPage });
        this.rerender();
    }

    mounted() {
        this.getList()
    }

    rerender() {
        this.table.reload('demo', {
            data: this.data.rows,
            curr: this.data.eachPage
        });

        //执行一个laypage实例
        this.laypage.render({
            elem: 'test1' //注意，这里的 test1 是 ID，不用加 # 号
            , limit: this.data.eachPage
            , layout: ["count", "prev", "page", "next", "limit"]
            , count: this.data.total //数据总数，从服务端得到
            , limits: [5, 10, 15]
            , curr: this.data.curPage
            , jump: async (obj, first) => {
                //obj包含了当前分页的所有参数，比如：

                //首次不执行
                if (!first) {
                    //do something
                    // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                    // console.log(obj.limit); //得到每页显示的条数

                    this.data.curPage = obj.curr
                    this.data.eachPage = obj.limit
                    const { curPage, eachPage } = this.data
                    this.data = await adminsApi.getList({ curPage, eachPage });

                    this.table.reload('demo', {
                        data: this.data.rows,
                        limit: this.data.eachPage
                    });
                }
            }
        });

    }
    handle() {
        this.table.on('tool(test)', async (obj) => { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
            if (layEvent === 'del') { //删除
                const { _id } = data
                const admin_id = sessionStorage.getItem("admin_id")
                if (_id === admin_id) {
                    layer.open({
                        content: '是否删除此项'
                        , btn: ['确定', '取消']
                        , yes: async (index, layero) => {
                            //按钮【按钮一】的回调
                            const { _id } = data;
                            await adminsApi.deleteAdmin({ _id })
                            // this.mounted();
                            layer.close(index);
                            location.hash = "#/login"
                        }
                    });
                } else {
                    layer.msg('您没有权限删除其他管理员', {
                        offset: '15rem'
                        , icon: 2
                        , time: 1500
                    })
                }

            } else if (layEvent === 'edit') {
                const { _id } = data
                const admin_id = sessionStorage.getItem("admin_id")
                if (_id === admin_id) {
                    layer.open(
                        {
                            title: "编辑管理员",
                            type: 1,
                            content: `
                           <div class="add-box" style="padding:20px;">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">管理员名称</label>
                                    <div class="layui-input-inline">
                                        <input value="${data.adminName}" type="text" required="" lay-verify="required" placeholder="管理员名称" autocomplete="off" class="layui-input adminName">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">原密码</label>
                                    <div class="layui-input-inline">
                                        <input type="password" required="" lay-verify="required" placeholder="请输入原密码" autocomplete="off" class="layui-input oldPwd">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">新密码</label>
                                    <div class="layui-input-inline">
                                        <input type="password" required="" lay-verify="required" placeholder="请输入新密码" autocomplete="off" class="layui-input newPwd">
                                    </div>
                                </div>
                           </div>
                        `,
                            btn: ['保存', '取消'],
                            yes: async (index, layero) => {
                                //按钮【按钮一】的回调
                                this._id = data._id

                                const msg = {
                                    _id: this._id,
                                    adminName: $(".adminName").val(),
                                    adminPassword: $(".newPwd").val()
                                }
                                // console.log(msg);
                                if ($(".layui-layer-btn0").hasClass("no") || $(".newPwd").val() == "") {
                                    layer.msg('输入信息有误', {
                                        offset: '10rem'
                                        , icon: 2
                                        , time: 1500
                                    })
                                } else {
                                    console.log(msg);
                                    await adminsApi.updatePwd(msg);
                                    layer.close(index);
                                }
                            },
                            success() {
                                $(".layui-layer-btn0").addClass("no")
                                $(".oldPwd").on("blur", async function () {
                                    let msg = {
                                        adminPassword: $(this).val(),
                                        _id: data._id
                                    }
                                    const flag = await adminsApi.checkPwd(msg);
                                    if (!flag) {
                                        layer.tips('原密码错误，请重新输入', this, {
                                            tips: 1,
                                            time: 1500
                                        });
                                    } else {
                                        $(".layui-layer-btn0").removeClass("no")
                                    }
                                })
                            }
                        }
                    )
                } else {
                    layer.msg('您没有权限编辑其他管理员', {
                        offset: '15rem'
                        , icon: 2
                        , time: 1500
                    })
                }
            }
        });
    }
}